<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Users extends Public_Controller
{
	public $data = array();
	
        function __construct() {
       
            parent::__construct();
            $this->load->model('user_model');
            // Load library
            $this->load->library('form_validation');

        }
    
	// Create
	function add()
	{	    
	    // Validate form
	    $this->form_validation->set_rules('userEmail', 'email', 'trim|required|valid_email');
	    $this->form_validation->set_rules('userPassword', 'password', 'trim|required|min_length[6]');
	    $this->form_validation->set_rules('userType', 'type', 'trim|required');
	    $this->form_validation->set_rules('userStatus', 'status', 'trim|required');
	    
	    if($this->form_validation->run())
	    {
	        // Validation passes
	        $userId = $this->user_model->AddUser($_POST);
	        
	        if($userId)
	        {
	            $this->session->set_flashdata('flashConfirm', 'The user has been successfully added.');
	            redirect('users');
	        }
	        else
	        {
                $this->session->set_flashdata('flashError', 'A database error has occured, please contact your administrator.');
	            redirect('users');
	        }
	    }
	    
	    $this->load->view('users/users_add_form');
	}
	
    // Retrieve
	function index($offset = 0)
	{
	    $this->load->library('pagination');
	    
	    $perpage = 1;
	    
	    $config['base_url'] = base_url() . 'users/index/';
	    $config['total_rows'] = $this->user_model->GetUsers(array('count' => true));
	    $config['per_page'] = $perpage;
	    $config['uri_segment'] = 3;
	    
	    $this->pagination->initialize($config);
	    
	    $data['pagination'] = $this->pagination->create_links();
	    
		$data['users'] = $this->user_model->GetUsers(array('limit' => $perpage, 'offset' => $offset));
		
		$this->load->view('users/users_index', $data);
	}
	
	// Update
	function edit($userId)
	{
	    $data['user'] = $this->user_model->GetUsers(array('userId' => $userId));
	    if(!$data['user']) redirect('users');

	    // Validate form
	    $this->form_validation->set_rules('userEmail', 'email', 'trim|required|valid_email');
	    $this->form_validation->set_rules('userPassword', 'password', 'trim|min_length[6]');
	    $this->form_validation->set_rules('userType', 'type', 'trim|required');
	    $this->form_validation->set_rules('userStatus', 'status', 'trim|required');
	    
	    if($this->form_validation->run())
	    {
	        // Validation passes
	        $_POST['userId'] = $userId;
	        if(empty($_POST['userPassword'])) unset($_POST['userPassword']);
	        
	        if($this->user_model->UpdateUser($_POST))
	        {
	            $this->session->set_flashdata('flashConfirm', 'The user has been successfully updated.');
	            redirect('users');
	        }
	        else
	        {
                $this->session->set_flashdata('flashError', 'A database error has occured, please contact your administrator.');
	            redirect('users');
	        }
	    }
	    
	    $this->load->view('users/users_edit_form', $data);
	}
	
	// Delete
	function delete($userId)
	{
	    $data['user'] = $this->user_model->GetUsers(array('userId' => $userId));
	    if(!$data['user']) redirect('users');
	    
	    $this->user_model->UpdateUser(array(
	        'userId' => $userId,
	        'userStatus' => 'deleted'
	    ));
	    
	    $this->session->set_flashdata('flashConfirm', 'The user has been successfully deleted.');
	    redirect('users');
	}
	
	function login()
	{
                $is_logged_in = $this->session->userdata('user_id')?$this->session->userdata('user_id'):'';
                if($is_logged_in) redirect ('admin');
                    
		if ($this->input->post())
		{
			// Validation data request
			$this->form_validation->set_rules('user_email', 'email', 'trim|required|valid_email');
			$this->form_validation->set_rules('user_password', 'password', 'trim|required');
                        
			
			if($this->form_validation->run())
			{
				// the form has successfully validated
				if($this->user_model->user_login(array('user_email' => $this->input->post('user_email'), 'user_password' => $this->input->post('user_password'))))
				{
                                        $return = $this->input->post('return');
					if($return) redirect ($return);
                                        else  redirect ('index');
				} 
				
			}
			
			$this->session->set_flashdata('Error', 'Login error.');
			
		}
		$this->data['title'] = "Login page";
		$this->load->view('users/users_login_form', $this->data)	;
		
	}
	
	public function logout($return = '')
	{
		// Clear session
	    $this->session->sess_destroy();
            if($return)
	    redirect($return);
            else redirect ('users/login');
	}
	
	function is_logined()
	{
		
	}
	
	public function _check_email_registry($userEmail)
	{
		if($this->input->post('userPassword'))
		{
			$user = $this->user_model->GetUsers(array('userEmail' => $userEmail, 'userPassword' => md5($this->input->post('userPassword'))));
			if($user) return true;
		}
		
		$this->form_validation->set_message('_check_email_registry', 'Your username / password combination is invalid.');
		return false;
	}
}